package com.runfast.waimai.web.controller;

import com.runfast.common.dao.model.RunfastAgentbusiness;
import com.runfast.common.dao.model.RunfastCuser;
import com.runfast.common.dao.model.RunfastDeliverCost;
import com.runfast.common.security.spring.UserDataDetails;
import com.runfast.common.service.RunfastAgentbusinessService;
import com.runfast.common.service.RunfastDeliverCostService;
import com.runfast.common.utils.GPSUtil;
import com.runfast.common.utils.TokenUtil;
import com.runfast.common.web.entity.Result;
import com.runfast.common.web.entity.ResultCode;
import com.runfast.paotui.mq.AmqpClient;
import com.runfast.waimai.dao.model.*;
import com.runfast.waimai.entity.Cart;
import com.runfast.waimai.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 外卖订单接口
 */
@RestController("userWmHomeController")
@RequestMapping(value = "/api/user/wm/home")
public class HomeController {


    @Autowired
    private BsTravelAdvertService advertService;


    @Autowired
    private RunfastAgentbusinessService agentbusinessService;

    @Autowired
    private RunfastBusinessService businessService;

    @Autowired
    private RunfastHomepageService homepageService;


    @Autowired
    private RunfastGoodsSellService goodsSellService;


    @Autowired
    private RunfastActivityService activityService;


    @Autowired
    private RunfastGoodsSellRecordService orderService;

    @Autowired
    private CartService cartService;


    @Autowired
    private RunfastBusinessTypeService businessTypeService;

    @Autowired
    private RunfastDeliverCostService deliverCostService;

    @Autowired
    private AmqpClient amqpClient;

    /**
     * 根据用户当前的位置获取默认的代理商
     *
     * @param userLng 用户当前的经度
     * @param userLat 用户当前的纬度
     * @return
     */
    @PostMapping("/agent")
    public Result agent(@RequestParam double userLng, @RequestParam double userLat) {
/**
 * 高德转百度
 */
//        double[] to = GPSUtil.gcj02_To_Bd09(userLat, userLng);
//        userLng = to[1];
//        userLat = to[0];
        RunfastAgentbusiness agentNearBy = agentbusinessService.getAgentNearByRange(userLng, userLat);

        if (agentNearBy != null) return Result.ok("", agentNearBy);
        else return Result.fail(ResultCode.FAIL, "附近不存在代理商");

    }

    /**
     * 获取附近商家
     *
     * @param userLng         用户当前经度
     * @param userLat         用户当前维度
     * @param sorting         排序方式
     * @param activityType    活动类型
     * @param catalogId       商户分类id
     * @param businessFeature 商家特色，0：快车专送；1：商家配送；2：支持自取，3：金牌商家，4：新商家，5：零元起送，6：营业中
     * @param pageable
     * @return
     */
        @PostMapping("/businessNearBy")
    public Result<List<Map<String, Object>>> businessNearBy(@RequestParam Integer agentId, @RequestParam double userLng, @RequestParam double userLat, @RequestParam Integer sorting, @RequestParam(required = false) List<Integer> activityType, @RequestParam(required = false) List<Integer> catalogId, @RequestParam(required = false) Integer businessFeature, @PageableDefault Pageable pageable) {
/**
 * 高德转百度
 */
        double[] to = GPSUtil.gcj02_To_Bd09(userLat, userLng);
        userLng = to[1];
        userLat = to[0];
        List<Map<String, Object>> maps = businessService.nearBy(agentId, 5000, userLng, userLat, sorting, activityType, catalogId, businessFeature, pageable);
        if(maps.size()<=0) {
            if (catalogId != null && !catalogId.isEmpty()) {
                catalogId = null;
                maps = businessService.nearBy(agentId, 5000, userLng, userLat, sorting, activityType, catalogId, businessFeature, pageable);
            }
        }

        return Result.ok("", maps);
    }

    /**
     * 获取代理商促销信息
     *
     * @param agentId 代理商id
     * @return
     */
    @PostMapping("/page")
    public Result<Map<String, Object>> page(@RequestParam double userLng, @RequestParam double userLat, @RequestParam int agentId) {
/**
 * 高德转百度
 */
        double[] to = GPSUtil.gcj02_To_Bd09(userLat, userLng);
        userLng = to[1];
        userLat = to[0];
        /**
         * 根据代理商id获取首页轮播广告列表
         */
        BsTravelAdvertExample advertExample = new BsTravelAdvertExample();
        advertExample.or().andLocationEqualTo(1).andUsedEqualTo(1).andAgentIdEqualTo(agentId).andTypeEqualTo(0);

        List<BsTravelAdvert> advertList = advertService.selectByExample(advertExample);


        /**
         * 根据代理商id获取首页商户分类
         */
        RunfastHomepageExample homepageExample = new RunfastHomepageExample();
        homepageExample.or().andAgentIdEqualTo(agentId);
        homepageExample.setOrderByClause("sort desc");
        List<RunfastHomepage> homepageList = homepageService.selectByExample(homepageExample);

        /**
         *获取代理商优惠专区大额满减或者免配送费活动
         */
        List<Integer> activityTypeList = new ArrayList<>();
        activityTypeList.add(1);//满减
        activityTypeList.add(5);//免全部
        activityTypeList.add(7);//免全部
        List<RunfastActivity> agentZoneBusiness = activityService.getAgentZoneActivityIn(agentId, activityTypeList);

        /**
         * 获取特惠优选商品列表
         */
        RunfastDeliverCost defaultDeliveryTemplate = deliverCostService.getDefaultDeliveryTemplate(agentId);
        Date deliveryStart1 = defaultDeliveryTemplate.getStartTimeDay1();
        Date deliveryEnd1 = defaultDeliveryTemplate.getEndTimeDay1();
        Date deliveryStart2 = defaultDeliveryTemplate.getStartTimeNight2();
        Date deliveryEnd2 = defaultDeliveryTemplate.getEndTimeNight2();
        List<Map<String, Object>> offZoneGoods = goodsSellService.findAgentOffZoneGoods(agentId, userLng, userLat, deliveryStart1, deliveryEnd1, deliveryStart2, deliveryEnd2, PageRequest.of(0, 8));

        Integer cartItemCount = 0;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) {
            UserDataDetails<RunfastCuser> userDataDetails = (UserDataDetails<RunfastCuser>) authentication.getPrincipal();
            RunfastCuser cuser = userDataDetails.getData();
            List<Cart> cartList = cartService.list(cuser.getId(),null);
            for (Cart cart : cartList) {
                cartItemCount += cart.getTotalNum();
            }

        }


        Map<String, Object> page = new HashMap<>();

        page.put("cartItemCount", cartItemCount);
        page.put("advertList", advertList);
        page.put("homepageList", homepageList);
        page.put("agentZoneBusiness", agentZoneBusiness);
        page.put("offZoneGoods", offZoneGoods);
        return Result.ok("", page);
    }


    /**
     * 根据名称搜索商家或者商品
     *
     * @param userLng  用户当前经度
     * @param userLat  用户当前纬度
     * @param name     商家名或者商品名
     * @param agentId  代理商id
     * @param pageable
     * @return
     */
    @PostMapping("/search")
    public Result<List<Map<String, Object>>> search(@RequestParam int agentId, @RequestParam String name, @RequestParam Double userLng, @RequestParam Double userLat, @PageableDefault Pageable pageable) {
/**
 * 高德转百度
 */
        double[] to = GPSUtil.gcj02_To_Bd09(userLat, userLng);
        userLng = to[1];
        userLat = to[0];
        List<Map<String, Object>> search = businessService.search(name, agentId, userLng, userLat, pageable);

        return Result.ok("", search);
    }


    /**
     * 获取参与大额满减专区活动的商家分页列表
     *
     * @param agentId
     * @param userLng
     * @param userLat
     * @param pageable
     * @return
     */
    @PostMapping("/fullLessZoneBusiness")
    public Result fullLessZoneBusiness(@RequestParam Integer agentId, @RequestParam Double userLng, @RequestParam Double userLat, @PageableDefault Pageable pageable) {

        /**
         * 高德转百度
         */
        double[] to = GPSUtil.gcj02_To_Bd09(userLat, userLng);
        userLng = to[1];
        userLat = to[0];

        List<Integer> activityTypeList = new ArrayList<>();
        activityTypeList.add(1);//满减
        List<RunfastActivity> agentZoneBusiness = activityService.getAgentZoneActivityIn(agentId, activityTypeList);

        if (agentZoneBusiness.isEmpty()) return Result.ok("");
        RunfastActivity activity = agentZoneBusiness.get(0);

        return businessService.getAgentZoneBusiness(activity.getId(), userLng, userLat, pageable);
    }

    /**
     * 获取参与免配送费专区活动的商家分页列表
     *
     * @param agentId
     * @param userLng
     * @param userLat
     * @param pageable
     * @return
     */
    @PostMapping("/freeDeliveryZoneBusiness")
    public Result freeDeliveryZoneBusiness(@RequestParam Integer agentId, @RequestParam Double userLng, @RequestParam Double userLat, @PageableDefault Pageable pageable) {

        /**
         * 高德转百度
         */
        double[] to = GPSUtil.gcj02_To_Bd09(userLat, userLng);
        userLng = to[1];
        userLat = to[0];

        List<Integer> activityTypeList = new ArrayList<>();
        activityTypeList.add(5);//免全部
        activityTypeList.add(7);//免部分
        List<RunfastActivity> agentZoneBusiness = activityService.getAgentZoneActivityIn(agentId, activityTypeList);

        if (agentZoneBusiness.isEmpty()) return Result.ok("");
        RunfastActivity activity = agentZoneBusiness.get(0);

        return businessService.getAgentZoneBusiness(activity.getId(), userLng, userLat, pageable);
    }


    /**
     * 获取特惠优选专区商家列表
     *
     * @param agentId
     * @param userLng
     * @param userLat
     * @param pageable
     * @return
     */
    @PostMapping("/offZoneMoreBusiness")
    public Result<List<Map<String, Object>>> offZoneMoreBusiness(@RequestParam Integer agentId, @RequestParam double userLng, @RequestParam double userLat, @PageableDefault Pageable pageable) {
/**
 * 高德转百度
 */
        double[] to = GPSUtil.gcj02_To_Bd09(userLat, userLng);
        userLng = to[1];
        userLat = to[0];
        List<Integer> activityTypeList = new ArrayList<>();

        activityTypeList.add(2);
        activityTypeList.add(4);
        List<Map<String, Object>> businessList = businessService.offZoneMoreBusiness(agentId, 5000, userLng, userLat, activityTypeList, pageable);

        return Result.ok("", businessList);
    }


    /**
     * 当前用户可以领取的红包列表
     *
     * @param agentId
     * @param pageable
     * @param token
     * @return
     */
    @PostMapping("/redActivityForPick")
    public Result<List<RunfastActivity>> redActivityForPick(@RequestParam Integer agentId, @PageableDefault Pageable pageable, @RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);

        return activityService.redActivityForPick(agentId, userId, true);
    }


    /**
     * 获取最近订单
     *
     * @param agentId
     * @return
     */
    @PostMapping("/latestOrder")
    public Result latestOrder(@RequestParam Integer agentId) {

        UserDataDetails<RunfastCuser> principal = (UserDataDetails<RunfastCuser>) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        RunfastCuser cuser = principal.getData();

        RunfastGoodsSellRecordExample goodsSellRecordExample = new RunfastGoodsSellRecordExample();
        goodsSellRecordExample.or().andAgentIdEqualTo(agentId).andUserIdEqualTo(cuser.getId());

        goodsSellRecordExample.setOrderByClause("id desc");
        Map<String, Object> lastestOrder = orderService.findLastestOrder(agentId, cuser.getId());

        if (lastestOrder != null) {
            Integer businessId = (Integer) lastestOrder.get("businessId");

            Map<String, Object> businessMap = businessService.findImgById(businessId);
            lastestOrder.put("businessImg", businessMap.get("imgPath"));
        }


        return Result.ok("", lastestOrder);
    }


    /**
     * 商家子分类列表
     *
     * @return
     */
    @PostMapping("/businessSubTypes")
    public Result businessSubTypes(@RequestParam Integer parentTypeId) {
        RunfastBusinessTypeExample businessTypeExample = new RunfastBusinessTypeExample();
        businessTypeExample.or().andParent_idEqualTo(parentTypeId);
        List<RunfastBusinessType> subTypeList = businessTypeService.selectByExample(businessTypeExample);

        return Result.ok("", subTypeList);
    }


    @PostMapping("/sendMq")
    public Result sendMq(String queue) {

        amqpClient.publish(queue, new RunfastGoodsSellRecord());

        return Result.ok("");
    }


}
